﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;

namespace PracticeAzure.Website.Models
{
    public class CorrigendumCreateViewModel
    {
        [Required(ErrorMessage = "标题不能为空")]
        public string Title { get; set; }

        [Required(ErrorMessage = "正文不能为空")]
        public string Body { get; set; }

        public IEnumerable<HttpPostedFileBase> Attachments { get; set; }

        public CorrigendumCreateViewModel()
        {
            Attachments = new List<HttpPostedFileBase>();
        }

        internal class ModelBinder : IModelBinder
        {
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                // bind the mornal properties by the default binder
                // since we use the jquery html editor here we do not validate the request
                var defaultBinder = new DefaultModelBinder();
                var model = defaultBinder.BindModel(controllerContext, bindingContext);
                // bind the uploaded files
                var files = new List<HttpPostedFileBase>();
                for (var i = 0; i < controllerContext.HttpContext.Request.Files.Count; i++)
                {
                    var file = controllerContext.HttpContext.Request.Files[i];
                    if (!string.IsNullOrWhiteSpace(file.FileName) && file.ContentLength > 0)
                    {
                        files.Add(file);
                    }
                }
                var attachment = bindingContext.ModelType.GetProperty("Attachments");
                attachment.SetValue(model, files, null);
                return model;
            }
        }
    }
}